function sendRequest(path) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE) {
                return
            }
            try {
                const resJSON = JSON.parse(xhr.response)
                console.log('response: ', resJSON)
                resolve(resJSON)
            } catch (e) {
                console.error(e)
                reject(e);
            }
        }
        const origin = window.location.origin
        xhr.open('get', `${origin}${path}`)
        xhr.send()
    })
}

function appendOnline(origin_data) {
    const { name, device_id } = origin_data;

    const statusEle = document.getElementById("status")
    const ele = document.createElement("div")

    const time = new Date().toLocaleString()
    ele.innerHTML = `<div class="online">
            <span class="user">${time}  ${device_id}(${name})已上线</span>
        </div>`

    ele.className = "msg"
    statusEle.appendChild(ele)

    setTimeout(() => {
        statusEle.removeChild(ele)
    }, 3000)
}

function appendMsg(origin_data) {
    console.log(origin_data)

    const origin_msg = origin_data.msg;
    const origin_user_config = origin_data.user_config;
    const origin_device_config = origin_data.device_config;
    const origin_device_info = origin_data.device_info;
    const time = origin_msg.time || new Date(origin_data.create_time).toLocaleString()

    let machine = origin_device_info.machine || "";
    if (machine) {
        machine += ': '
    }

    const device_id = machine + origin_device_info.device_id;
    const username = origin_user_config.name;
    const email = origin_user_config.email;
    let avatar = origin_user_config.avatar;
    const content = origin_msg.content;
    let sendTime = time
    let ip = "0.0.0.0"

    if (origin_device_info.ip) {
        ip = origin_device_info.ip
    }

    //console.log(sendTime)

    if (!avatar) {
        avatar = "https://cdn.hanxiaoxin.cn/iot/esp32/http-server/images/headphoto/kanshan.png"
    }

    if (content) {
        const msgEle = document.getElementById("messages")
        const ele = document.createElement("div")


        ele.innerHTML = `<div class="msg-item">
            <div class="avatar-box">
                <img class="avatar" src="${avatar}" alt="头像" />
                <div class="user">
                    <span class="name">${username}</span>
                    <span class="id">${device_id} ip:${ip}</span>
                </div>
            </div>
            <span class="content"><span class="time">${sendTime}</span> <span class="msg-content">${content}</span></span>
        </div>`

        ele.className = "msg"
        msgEle.appendChild(ele)
    }
}

window.sendRequest = sendRequest
window.appendOnline = appendOnline
window.appendMsg = appendMsg